import turtle


q = {
    "question": "整数在python中用什么表示",
    "answers": [
        {
            "title": "int"
        },
        {
            "title": 'str'
        },
        {
            "title": "float"
        },
    ],
    "right": "int"
}
def up_goto(x, y):
    """
    画笔抬起去移动到某个位置
    :param x: x坐标
    :param y: y坐标
    :return:
    """
    turtle.up()
    turtle.goto(x,y)
    turtle.down()

def draw():
    """编写知识问答图形界面"""
    up_goto(0, 100)
    turtle.write(q["question"], False, "center",
                 ("Arial", 24, "normal"))
    # 初始x坐标点
    x = -300
    # 每个值之前的间隔大小
    dis = 600/(len(q['answers'])-1)
    for i in range(len(q['answers'])):
        # 当前选项的中心坐标
        l_x = x+dis*i
        up_goto(l_x, -100)

        turtle.write(q["answers"][i].get("title"),True, 'center',
                     ("Arial", 24, "normal"))
        # 获取write后的坐标
        r_x = turtle.xcor()
        # 当前选项的左侧坐标
        q['answers'][i]['l_x'] = l_x-(r_x-l_x)
        # 当前选项的右侧的坐标
        q['answers'][i]['r_x'] = r_x

def func_click(x, y ):
    """鼠标监听事件"""
    up_goto(0,0)
    if -100< y < -50:
        # 遍历选项
        for i in range(len(q['answers'])):
            c_a = q["answers"][i]
            # 如果点击区域在选项内
            if c_a['l_x'] < x and x< c_a['r_x']:
                # 是否是正确答案
                if q['right'] == c_a['title']:
                    turtle.pencolor('green')
                    turtle.write("回答正确", False,
                                 "center", ("Arial", 24, 'normal'))
                    break
        else:
            turtle.pencolor('red')
            turtle.write("回答错误", False,
                         "center", ("Arial", 24, "normal"))


turtle.setup(800, 600)
draw()
turtle.onscreenclick(func_click)
print(q)
turtle.done()


